package cc.comac.mom.datahandlers.entity;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.EquipInventory;
import cc.comac.mom.bean.EquipInventoryBean;
import cc.comac.mom.bean.EquipWarehouseStock;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.dao.entity.EquipInventoryDao;
import cc.comac.mom.entity.EquipInventoryEntity;
import cc.comac.mom.entity.EquipInventorySpareRelationEntity;
import cc.comac.mom.entity.EquipSparePartMasterDataEntity;
import cc.comac.mom.entity.EquipWarehouseStockEntity;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.DataStatus;
import cc.comac.mom.util.ResultBean;

@Component
@Transactional
public class EquipInventoryDataHandler extends ServiceImpl<EquipInventoryDao, EquipInventoryEntity> {

	@Autowired
	private EquipInventoryDao equipInventoryDao;

	@Autowired
	private EquipInventorySpareRelationDataHandler equipInventorySpareRelationDataHandler;

	@Autowired
	private EquipSparePartMasterDataDataHandler equipSparePartMasterDataDataHandler;
	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;

	@Autowired
	private EquipWarehouseStockDataHandler equipWarehouseStockDataHandler;

	@Autowired
	private UniversalNumberGenerationDataHandler universalNumberGenerationDataHandler;

	// 盘点数据修改
	public ResultBean updateInventorySpare(EquipInventoryBean equipInventorybean) {
		ResultBean resultBean = new ResultBean(true);
		EquipInventoryEntity innerData = equipInventorybean.getEquipInventoryEntity();
		List<EquipInventorySpareRelationEntity> list = equipInventorybean.getList();
		long inventoryId = 0;
		if (innerData != null) {
			inventoryId = innerData.getId();
		} else {
			inventoryId = list.get(0).getInventoryId();
		}
		// 通过盘点主键查询盘点信息
		EquipInventoryEntity selectById = equipInventoryDao.selectById(inventoryId);
		// 当盘点数据不为空时
		if (innerData != null) {
			if (innerData.getId() == 0) {
				throw new RuntimeException("无法获取主键");
			}
			// 更新盘点数据
			int updateById = equipInventoryDao.updateById(innerData);
			if (updateById != 1) {
				throw new RuntimeException("编辑失败，编辑数量" + updateById);
			}
		}
		// 如果备件数据不为空时
		if (list.size() > 0) {
			List<EquipInventorySpareRelationEntity> saveList = new ArrayList<EquipInventorySpareRelationEntity>();
			List<EquipInventorySpareRelationEntity> updateList = new ArrayList<EquipInventorySpareRelationEntity>();
			for (EquipInventorySpareRelationEntity equipInventorySpareRelationEntity : list) {
				if (equipInventorySpareRelationEntity.getInventoryId() == 0) {
					throw new RuntimeException("盘点单号不可为0");
				}
				if (equipInventorySpareRelationEntity.getSparePartId()== 0) {
					throw new RuntimeException("备件编码不可为0");
				}
				if (equipInventorySpareRelationEntity.getId() == 0) {
					baseEntityDataUtil.setBaseEntityData(equipInventorySpareRelationEntity);
					saveList.add(equipInventorySpareRelationEntity);
				}else {
					baseEntityDataUtil.updateBaseEntityData(equipInventorySpareRelationEntity);
					updateList.add(equipInventorySpareRelationEntity);
				}
				// 校验当前位置编码是否改动，改动后是否和库存中的数据冲突
				boolean validateLocationIsExist = equipWarehouseStockDataHandler.validateLocationIsExist(selectById.getWarehouseName(),
						equipInventorySpareRelationEntity.getId(),
						equipInventorySpareRelationEntity.getCurrentLocationCode());
				if (!validateLocationIsExist) {
					throw new RuntimeException("修改的当前位置"+equipInventorySpareRelationEntity.getCurrentLocationCode()+"库存中已存在！");
				}
				baseEntityDataUtil.updateBaseEntityData(equipInventorySpareRelationEntity);
			}
			if (updateList.size() > 0) {
				equipInventorySpareRelationDataHandler.updateBatchById(list, list.size());
			}
			if (saveList.size() > 0) {
				equipInventorySpareRelationDataHandler.saveBatch(saveList, saveList.size());
			}
		}
		return resultBean;
	}

	// 批量逻辑删除
	public ResultBean batchDelete(List<EquipInventory> list) {
		ResultBean resultBean = new ResultBean(true);
		List<EquipInventoryEntity> inventoryList = new ArrayList<EquipInventoryEntity>();
		for (EquipInventory equipInventory : list) {
			EquipInventoryEntity innerData = equipInventory.getInnerData();
			if (innerData == null) {
				throw new RuntimeException("无法获取编辑数据");
			}
			if (innerData.getId() == 0) {
				throw new RuntimeException("无法获取主键");
			}
			innerData.setRowStatus(0);
			inventoryList.add(innerData);
		}
		if (inventoryList.size() > 0) {
			boolean updateBatchById = updateBatchById(inventoryList, inventoryList.size());
			if (!updateBatchById) {
				throw new RuntimeException("删除失败！");
			}
		}
		return resultBean;
	}

	/**
	 * 保存盘点数据
	 **/
	public ResultBean saveInventoryAndSpareData(EquipInventoryBean equipInventoryBean) {
		ResultBean resultBean = new ResultBean(true);
		EquipInventoryEntity equipInventoryEntity = equipInventoryBean.getEquipInventoryEntity();
		List<EquipInventorySpareRelationEntity> list = equipInventoryBean.getList();
		// 判断盘点单号是否存在
		if (StringUtils.isEmpty(equipInventoryEntity.getInventoryNumber())) {
			equipInventoryEntity.setInventoryNumber(universalNumberGenerationDataHandler
					.numberGeneration(universalNumberGenerationDataHandler.getInventoryNumberGeneration()));
		}
		// 保存盘点数据
		equipInventoryEntity.setStatus(DataStatus.UNCONFIRMED);
		baseEntityDataUtil.setBaseEntityData(equipInventoryEntity);
		int insert = equipInventoryDao.insert(equipInventoryEntity);
		if (insert != 1) {
			throw new RuntimeException("新增单据失败，新增数量" + insert);
		}
		// 更新盘点备件关联数据
		if (list.size() > 0) {
			for (EquipInventorySpareRelationEntity entity : list) {
				if (StringUtils.isEmpty(entity.getCurrentLocationCode())) {
					throw new RuntimeException("当前位置编码不能为空");
				}
				if (entity.getAcutualCount() == 0) {
					throw new RuntimeException("实际数量不能为0");
				}
				if (entity.getSparePartId() == 0) {
					throw new RuntimeException("当前无选中备件！");
				}
				baseEntityDataUtil.setBaseEntityData(entity);
				entity.setInventoryId(equipInventoryEntity.getId());
				// 查询备件数据通过备件id
				EquipSparePartMasterDataEntity selectPartMasterDataById = equipSparePartMasterDataDataHandler
						.selectPartMasterDataById(entity.getSparePartId());
				if (!entity.getCurrentLocationCode().equals(entity.getSourceLocation())) {
					boolean validateLocationIsExist = validateLocationIsExist(equipInventoryEntity.getWarehouseName(),
							entity.getSparePartId(), entity.getCurrentLocationCode());
					if (!validateLocationIsExist) {
						throw new RuntimeException("仓库 " + equipInventoryEntity.getWarehouseName() + " 下备件的备件  "
								+ selectPartMasterDataById.getSparePartName() + " 位置下的" + entity.getCurrentLocationCode()
								+ " 已存在！");
					}
				}
			}
			// 批量新增盘点和入库单关联数据
			boolean batchInsertData = equipInventorySpareRelationDataHandler.batchInsertData(list);
			if (!batchInsertData) {
				throw new RuntimeException("新增备件数据失败！");
			}
		}
		return resultBean;
	}

	/**
	 * 更新当前盘点数据下的备件的库存数量
	 **/
	public ResultBean spareInWarehouseUpdateQuantity(EquipInventory equipInventory) throws RuntimeException {
		ResultBean resultBean = new ResultBean(true);
		long id = equipInventory.getInnerData().getId();
		// 查询当前数据
		EquipInventoryEntity equipInventoryEntity = equipInventoryDao.selectById(id);

		// 通过盘点id查询盘点下所有备件数据
		ResultDev selectSpareDataByInventotyId = equipInventorySpareRelationDataHandler
				.selectSpareDataByInventotyId(id);
		@SuppressWarnings("unchecked")
		List<EquipInventorySpareRelationEntity> list = (List<EquipInventorySpareRelationEntity>) selectSpareDataByInventotyId
				.getEntityList();
		if (list.size() > 0) {
			ArrayList<EquipSparePartMasterDataEntity> masterList = new ArrayList<EquipSparePartMasterDataEntity>();
			for (EquipInventorySpareRelationEntity equipInventorySpareRelationEntity : list) {
				EquipSparePartMasterDataEntity entity = new EquipSparePartMasterDataEntity();
				entity.setTotalAmount(equipInventorySpareRelationEntity.getDifCount());
				entity.setId(equipInventorySpareRelationEntity.getSparePartId());
				masterList.add(entity);
			}
			equipSparePartMasterDataDataHandler.batchUpdateCountById(masterList);
			ArrayList<EquipWarehouseStock> arrayList = new ArrayList<EquipWarehouseStock>();
			for (EquipInventorySpareRelationEntity equipInventorySpareRelationEntity : list) {
				EquipWarehouseStock equipWarehouseStock = new EquipWarehouseStock();
				EquipWarehouseStockEntity entity = new EquipWarehouseStockEntity();
				entity.setQuantity(equipInventorySpareRelationEntity.getAcutualCount());
				entity.setSparePartId(equipInventorySpareRelationEntity.getSparePartId());
				entity.setWarehouseName(equipInventoryEntity.getWarehouseName());
				entity.setLocation(equipInventorySpareRelationEntity.getSourceLocation());
				equipWarehouseStock.setInnerData(entity);
				equipWarehouseStock.setCurrentLocation(equipInventorySpareRelationEntity.getCurrentLocationCode());
				arrayList.add(equipWarehouseStock);
			}
			boolean changeQuatityBySpareIdAndWarehouseId = equipWarehouseStockDataHandler
					.changeQuatityBySpareIdAndWarehouseId(arrayList);
			if (!changeQuatityBySpareIdAndWarehouseId) {
				throw new RuntimeException("更新盘点库存失败");
			}
			// 更新备件盘点状态为已确认
			equipInventoryEntity.setStatus(DataStatus.CONFIRMED);
			equipInventoryDao.updateById(equipInventoryEntity);

		}
		return resultBean;
	}

	/**
	 * 批量 更新当前盘点数据下的备件的库存数量
	 **/
	public ResultBean batchSpareInWarehouseUpdateQuantity(List<EquipInventory> list) throws RuntimeException {
		ResultBean resultBean = new ResultBean(true);
		for (EquipInventory equipInventory : list) {
			spareInWarehouseUpdateQuantity(equipInventory);
		}
		return resultBean;
	}

	// 校验库存中当前仓库下当前备件下位置编码新增或者编辑的备件是否存在
	public boolean validateLocationIsExist(String WarehouseName, long spareId, String location) {
		return equipWarehouseStockDataHandler.validateLocationIsExist(WarehouseName, spareId, location);
	}

	public ResultDev selectBySomeFields(EquipInventory equipInventory) {
		ResultDev resultDev = new ResultDev();
		EquipInventoryEntity innerData = equipInventory.getInnerData();
		if (equipInventory.getPageNum() == 0) {
			equipInventory.setPageNum(1);
		}

		if (equipInventory.getPageSize() == 0) {
			equipInventory.setPageSize(10);
		}
		QueryWrapper<EquipInventoryEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.orderByDesc("creation_time");
		if (StringUtils.isNotEmpty(innerData.getInventoryNumber())) {
			queryWrapper.like("inventory_number", innerData.getInventoryNumber());
		}
		if (StringUtils.isNotEmpty(innerData.getWarehouseName())) {
			queryWrapper.like("warehouse_name", innerData.getWarehouseName());
		}
		if (StringUtils.isNotEmpty(innerData.getAgent())) {
			queryWrapper.like("agent", innerData.getAgent());
		}
		Page<EquipInventoryEntity> page = new Page<>(equipInventory.getPageNum(), equipInventory.getPageSize(), true);
		IPage<EquipInventoryEntity> selectPage = equipInventoryDao.selectPage(page, queryWrapper);

		resultDev.setEntityList(selectPage.getRecords());
		resultDev.setPageCount((int) selectPage.getPages());
		resultDev.setTotalQuantity((int) selectPage.getTotal());
		return resultDev;
	}

	public ResultDev selectAll() {
		ResultDev resultDev = new ResultDev();
		QueryWrapper<EquipInventoryEntity> queryWrapper = new QueryWrapper<EquipInventoryEntity>();
		queryWrapper.eq("row_status", 1);
		List<EquipInventoryEntity> selectList = equipInventoryDao.selectList(queryWrapper);
		resultDev.setEntityList(selectList);
		return resultDev;
	}

}
